<?php

namespace App\Task;

use App\Model\DataBackhaulSetting;
use App\Model\DataPaymentBackhaul;
use App\Model\DataSpread;
use App\Model\DataUserJuliangTokenRel;
use App\Model\Payment;
use App\Model\SystemOrderDay;
use GuzzleHttp\Client;
use Hyperf\Crontab\Annotation\Crontab;
use Hyperf\DbConnection\Db;
use Hyperf\Logger\LoggerFactory;
use Hyperf\Utils\ApplicationContext;
use Psr\Log\LoggerInterface;


//#[Crontab(name: "backhaulOrderTask", rule: "*/30 * * * * *", callback: "execute", memo: "回传上报订单'")]
//#[Crontab(name: "UploadtOrderTask", rule: "*/1 * * * *", callback: "execute", memo: "发送订单消息到统计后台'")]
class UploadtOrderTask
{
    protected LoggerInterface $logger;

    public static $upOrderLink = "https://novel.kuaiyingbox.com/api/pay-kywjy";

    public static $upOrderdyLink = "https://novel.kuaiyingbox.com/api/pay-kydj";

    public static $upOrderdytLink = "https://novel.kuaiyingbox.com/api/pay-lldj";

    public function __construct(protected LoggerFactory $loggerFactory)
    {
        $this->logger = $this->loggerFactory->get('log', 'UploadOrder');
    }

    public function execute()
    {
        $container = ApplicationContext::getContainer();
        $redis = $container->get(\Hyperf\Redis\RedisFactory::class)->get('default');

        try {
            $select_order_id = 0;
            $orderKey =  'upload_order_nums_order_new_data_tw';
            $getOrderkey = $redis->get($orderKey);
            if(!empty($getOrderkey)){
                $select_order_id = $getOrderkey;
            }
            $select_dy_order_id = 0;
            $orderdyKey =  'upload_order_nums_order_new_data_tw_dy';
            $getOrderdykey = $redis->get($orderdyKey);
            if(!empty($getOrderdykey)){
                $select_dy_order_id = $getOrderdykey;
            }

            $select_dyt_order_id = 0;
            $orderdytKey =  'upload_order_nums_order_new_data_tw_dyt';
            $getOrderdytkey = $redis->get($orderdytKey);
            if(!empty($getOrderdytkey)){
                $select_dyt_order_id = $getOrderdytkey;
            }

            $this->logger->info(date('Y-m-d H:i:s') . '------------------------获得数据');

            $payment = Payment::query()->where('id','>',$select_order_id)->where(['status' => 2,'applet_id' => 10002])
                ->orderBy('id')->limit(100)->get()->toArray();

            if(!empty($payment)){
                $count = count($payment);
                $order_id = $payment[$count-1]['id'];

                foreach ($payment as $value) {
                    $order_id = $value['id'];
                }

                $this->logger->info(date('Y-m-d H:i:s') . '------------------------上传订单数据');
                $is_upload = $this->uploadOrder($payment);
                if(!empty($is_upload)){
                    $redis->set($orderKey,$order_id);
                }
            }

            $this->logger->info(date('Y-m-d H:i:s') . '------------------------获得数据');

            $payment = Payment::query()->where('id','>',$select_dy_order_id)->where(['status' => 2,'applet_id' => 20000])->limit(100)->orderBy('id')->get()->toArray();

            if(!empty($payment)){
                $count = count($payment);
                $order_id = $payment[$count-1]['id'];

                foreach ($payment as $value) {
                    $order_id = $value['id'];
                }

                $this->logger->info(date('Y-m-d H:i:s') . '------------------------上传订单数据');
                $is_upload = $this->uploadOrderdy($payment);
                if(!empty($is_upload)){
                    $redis->set($orderdyKey,$order_id);
                }
            }

            $this->logger->info(date('Y-m-d H:i:s') . '------------------------获得数据');

            $payment = Payment::query()->where('id','>',$select_dyt_order_id)->where(['status' => 2,'applet_id' => 20001])->limit(100)->orderBy('id')->get()->toArray();

            if(!empty($payment)){
                $count = count($payment);
                $order_id = $payment[$count-1]['id'];

                foreach ($payment as $value) {
                    $order_id = $value['id'];
                }

                $this->logger->info(date('Y-m-d H:i:s') . '------------------------上传订单数据');
                $is_upload = $this->uploadOrderdyt($payment);
                if(!empty($is_upload)){
                    $redis->set($orderdytKey,$order_id);
                }
            }

        }catch (\Exception $e){
            $this->logger->error('请求|错误：' . $e->getLine() . '|' . $e->getMessage());
        }
        $this->logger->info(date('Y-m-d H:i:s') . '------------------------结束定时获取数据');
    }
    public function object_to_array($obj){
        # 对象列表装好为空
        $new_array = [];
        if ($obj){
            foreach ($obj as $key=>$value){
                $new_array[$key] = (array)$value;
            }
        }
        return $new_array;
    }

    public function uploadOrder($params){
        $postparams = [
            'data' => $params
        ];
        $taskUrl = self::$upOrderLink;
        $this->logger->info('上传订单数据：'.PHP_EOL.var_export(['result' => $postparams], true));
        $this->logger->info('上传订单Url：'.$taskUrl);
        //开始上传
        $postResult  = $this->json_post($taskUrl,$postparams);
        $this->logger->info('上传订单详情接口成功 返回数据：'.PHP_EOL.var_export(['result' => $postResult], true));
        return true;

    }

    public function uploadOrderdy($params){
        $postparams = [
            'data' => $params
        ];
        $taskUrl = self::$upOrderdyLink;
        $this->logger->info('上传订单数据：'.PHP_EOL.var_export(['result' => $postparams], true));
        $this->logger->info('上传订单Url：'.$taskUrl);
        //开始上传
        $postResult  = $this->json_post($taskUrl,$postparams);
        $this->logger->info('上传订单详情接口成功 返回数据：'.PHP_EOL.var_export(['result' => $postResult], true));
        return true;

    }

    public function uploadOrderdyt($params){
        $postparams = [
            'data' => $params
        ];
        $taskUrl = self::$upOrderdytLink;
        $this->logger->info('上传订单数据：'.PHP_EOL.var_export(['result' => $postparams], true));
        $this->logger->info('上传订单Url：'.$taskUrl);
        //开始上传
        $postResult  = $this->json_post($taskUrl,$postparams);
        $this->logger->info('上传订单详情接口成功 返回数据：'.PHP_EOL.var_export(['result' => $postResult], true));
        return true;

    }
    /**
     * 传入数组进行HTTP POST请求
     */
    private function json_post($url, $data = NULL)
    {

        $curl = curl_init();

        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
        if(!$data){
            return 'data is null';
        }
        if(is_array($data))
        {
            $data = json_encode($data);
        }
        curl_setopt($curl, CURLOPT_POST, 1);
        curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
        curl_setopt($curl, CURLOPT_HEADER, 0);
        curl_setopt($curl, CURLOPT_HTTPHEADER,array(
            'Content-Type: application/json; charset=utf-8',
            'Content-Length:' . strlen($data),
            'Cache-Control: no-cache',
            'Pragma: no-cache'
        ));
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
        $res = curl_exec($curl);
        $errorno = curl_errno($curl);
        if ($errorno) {
            return $errorno;
        }
        curl_close($curl);
        return $res;

    }

}